/*
 * @Author: C.
 * @Date: 2024-04-11 15:46:13
 */
import { useNavigate } from 'react-router-dom';
import { Button, Input, Form, Dialog, Image } from 'react-vant';
import { getCodeImg, login } from '@/api/auth';
import { setToken } from '@/utils/auth';
export default function Login() {
  // 通过useSelector直接拿到store中定义的value
  const title = 'Speak Now';
  const [dform, setDform] = useState({
    tenantId: '000000',
    uuid: '',
  });
  // 编程式路由
  const navigate = useNavigate();
  const goHome = () => {
    navigate('/home');
  };
  const getImgCode = async () => {
    const { data } = await getCodeImg();
    const imgUrl = 'data:image/gif;base64,' + data.img;
    setDform({
      ...dform,
      uuid: data.uuid as string,
    });
    await Dialog.alert({
      title: '验证码',
      closeable: true,
      theme: 'round-button',
      message: <Image height="100" src={imgUrl} />,
    });
  };
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue({
      username: '',
      password: '',
      code: '',
    });
  }, []);
  const onFinish = async (values: any) => {
    const data = await login({ ...values, ...dform });
    setToken(data.data.access_token);
    goHome();
  };

  return (
    <>
      <div className=" h-screen w-screen flex flex-col items-center p-4 bg-banner justify-between pt-40 pb-40">
        <h1 className="bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500 text-5xl font-black font-mono">
          {title}
        </h1>
        <div className="overflow-hidden rounded-xl py-5">
          <Form
            form={form}
            onFinish={onFinish}
            footer={
              <div className="mt-20">
                <button className="custom-button">登录</button>
              </div>
            }
          >
            <Form.Item
              rules={[{ required: true, message: '请填写用户名' }]}
              name="username"
              label="用户名"
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '请填写密码' }]}
              name="password"
              label="密码"
            >
              <Input placeholder="请输入密码" type="password" />
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '请填写密码' }]}
              name="code"
              label="验证码"
            >
              <Input
                prefix="💁"
                suffix={
                  <Button size="small" type="primary" onClick={getImgCode}>
                    获取
                  </Button>
                }
                placeholder="请输入短信验证码"
              />
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  );
}
